<template>
    <div class="home container" id="fullscreen-container" ref="fullscreen">
      <slot name="card"></slot>
      <slot name="search"></slot>
      <div class="controlbox">
        <el-tooltip class="item" effect="dark" content="点击进行定位" placement="left-start">
          <i class="el-icon-map-location" style="color:blue;margin-top: 10px;" @click="drawImage"></i>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="点击开始绘制围栏" placement="left-start">
          <i class="el-icon-share" style="color:blue;margin-top: 10px;" @click="drawPolygon"></i>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="停止绘制围栏" placement="left-start">
          <i class="el-icon-video-pause" style="color:red;margin-top: 10px;" @click="stopPolygon"></i>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="清除围栏" placement="left-start">
          <i class="el-icon-delete" style="color:red;margin-top: 10px;" @click="clearDraw"></i>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="开始修改围栏" placement="left-start">
          <i class="el-icon-edit" style="color:blue;margin-top: 10px;" @click="startModify"></i>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="停止修改围栏" placement="left-start">
          <i class="el-icon-video-pause" style="color:yellowgreen;margin-top: 10px;" @click="endModify"></i>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="透明" placement="left-start">
          <i class="el-icon-star-off" style="color:yellowgreen;margin-top: 10px;" @click="setOpacity"></i>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="不透明" placement="left-start">
          <i class="el-icon-star-on" style="color:yellowgreen;margin-top: 10px;" @click="noOpacity"></i>
        </el-tooltip>
      </div>
      <div id="map" :style="{'width':mapWidth,'height':mapHeight}"></div>
      <el-tooltip ref="elTooltip" :append-to-body="false" class="item" effect="light" placement="left">
			<div slot="content">
				<div class="mapbox">
					<li @click="mapChangeHandler('0')" :class="models.active[0]?'activeStyle':''">
            <img src="../assets/image/dixing.jpg" width="100px" height="50px">
						<div class="on">地形地图</div>
					</li>
					<li @click="mapChangeHandler('1')" :class="models.active[1]?'activeStyle':''">
            <img src="../assets/image/yingxiang.jpg" width="100px" height="50px">
						<div class="on">影像地图</div>
					</li>
          <li @click="mapChangeHandler('2')" :class="models.active[2]?'activeStyle':''">
            <img src="../assets/image/yingxiang.jpg" width="100px" height="50px">
						<div class="on">离线影像</div>
					</li>
				</div>
			</div>
			<div class="map0"></div>
		</el-tooltip>
    </div>
  </template>
<script lang="ts">
import {Feature} from "ol";
import {Point } from "ol/geom";
import GeoJSON from "ol/format/GeoJSON";
import {Component, Vue, Prop, Watch, Emit, Ref} from 'vue-property-decorator';
import Draw from 'ol/interaction/Draw';
// import { getArea } from 'ol/sphere';
import { Polygon } from 'ol/geom';
import Modify from 'ol/interaction/Modify';
import {createMap,mapChangeType,loadGeoJson,
  createSource,
  pointImageStyle,
  createLayer,
  createStyle,
  formatArea
  
} from '@/utils/map'
@Component({})
export default class OpenMap extends Vue {
  @Ref('fullscreen') private fullscreen!:any;
  @Ref('elTooltip') private elTooltip!:any;
    models:any={
        map: null,
        mapLanLot:[ ],
        geoJsonLayer:null,
        geoJsonSource: null,
        positionCoord:null,
        positionLayers:null,
        active:[true,false,false],
        polygonArea: 0,
        modify:null,
        positionSource: createSource(),
        polygonSource: createSource(),
        draw:null,
    };
    @Prop() private mapWidth!:string;
    @Prop() private mapHeight!:string;
    @Prop() private vectorId!:string;
    @Prop() private position!:string;
    @Prop() private polygon!:string;


    initMap() {
      this.models.map = createMap([111.670801, 40.818311]);
    }


    singleclick() {
      this.models.map.on("singleclick", (e) => {
          // 判断是否点击在点上
          this.backMessage(e.coordinate[0] + ',' + e.coordinate[1]);
      });
    }

    mapChangeHandler(x){
      mapChangeType(this.models.map.getLayers(),x,this.models.active);
    }

    @Emit('polygonChange')
    polygonAreaHandler(val){
      return val;
    }

  
    getPolygon(){
      if(this.models.polygonSource){
        const features = this.models.polygonSource.getFeatures();
        if(features.length == 0){
          return null;
        }
        // 存储最终提取的 MultiPolygon 坐标数据
        const multiPolygons:any = [];

        features.forEach(feature => {
          // 获取要素的几何对象
          const geometry:any = feature.getGeometry();
          
          if (!geometry) return; // 跳过无几何信息的要素

          // 根据几何类型处理坐标
          switch (geometry.getType()) {
            case 'MultiPolygon':
              // 直接获取坐标（已经是三维数组结构）
              multiPolygons.push(geometry.getCoordinates());
              break;
              
            case 'Polygon':
              // 将单个 Polygon 转换为 MultiPolygon 格式（包装成三维数组）
              multiPolygons.push(geometry.getCoordinates());
              break;

            // 可选：处理其他几何类型或抛出警告
            default:
              console.warn('Unsupported geometry type:', geometry.getType());
          }
        });
        return JSON.stringify(multiPolygons);
      }
      return null;
    }


    startModify() {
				this.models.modify = new Modify({
					source: this.models.polygonSource,
				});

        this.models.modify.on('modifyend', (event) => {
          this.configPolygonArea(); // 触发自定义处理函数
        });
				this.models.map.addInteraction(this.models.modify);

		}

    setOpacity(){
      this.models.polygonLayer.setStyle(createStyle("transparent","darkgreen","red"))
    }

    noOpacity(){
      this.models.polygonLayer.setStyle(createStyle("orange","darkgreen","red"))
    }
		endModify() {
			if (this.models.modify !== null) {
					this.models.map.removeInteraction(this.models.modify);
          this.models.modify= null;
      }

      this.configPolygonArea();
    }

    configPolygonArea(){
      const features = this.models.polygonSource.getFeatures();
      if(features && features.length> 0){
        let area = 0;
        features.forEach(f =>{
            area += formatArea(f.getGeometry().getCoordinates());
        })
        this.models.polygonArea =area;
        this.polygonAreaHandler(this.models.polygonArea );
      }
    }
    
  drawImage() {
    if(!this.models.positionLayers){
      this.models.positionLayers = createLayer(this.models.positionSource,pointImageStyle('location'));
          this.models.map.addLayer(this.models.positionLayers);
    }
    this.models.positionSource.clear()
    // 停止上一次的绘制，没有此代码会出现重叠
    this.removeMaker();
    if (this.models.draw !== null) {
      this.models.map.removeInteraction(this.models.draw)
    }
    this.models.draw = new Draw({
      source: this.models.positionSource,
      type: 'Point',
    })
    this.models.map.addInteraction(this.models.draw)
    let coord: any;
    this.models.draw.on('drawend', (e) => {
      this.models.map.removeInteraction(this.models.draw)
      coord = e.feature.getGeometry().getCoordinates() //获取最后点坐标
      let flag = false;
      if(this.models.geoJsonSource){
        let geoJsonFeatures = this.models.geoJsonSource.getFeatures();
        for (let ft of geoJsonFeatures) {
          let polygonGeometry = ft.getGeometry();
          //判断是否在Geometry内
          flag = polygonGeometry.intersectsCoordinate(coord);
          if (flag) {
            break;
          }
        }
      }
      if(this.models.polygonSource){
        let polygonFeatures = this.models.polygonSource.getFeatures();
        for (let ft of polygonFeatures) {
          let polygonGeometry = ft.getGeometry();
          //判断是否在Geometry内
          flag = polygonGeometry.intersectsCoordinate(coord);
          if (flag) {
            break;
          }
        }
      }
        if (flag) {
          this.$message({type: 'success',duration: 1000,message: '位置正确' + coord});
          this.models.positionCoord = coord;
          this.backMessage(coord[0] + ',' + coord[1]);
          this.setMarker(coord);
        } else {
          this.$message({type: 'error',duration: 1000,message: '位置不正确，不在区划内'})
        }
      });
    }


    removeMaker(){
      if(this.models.positionSource){
        this.models.positionSource.clear();
      }
    }

    drawPolygon() {
      this.models.polygonArea  = 0;
      if(!this.models.polygonLayer){
          
          this.models.polygonLayer = createLayer(this.models.polygonSource,createStyle("orange","darkgreen","red"));
          this.models.map.addLayer(this.models.polygonLayer);

      }
      this.models.polygonSource?.clear();
      if (this.models.draw !== null) {
        this.models.map.removeInteraction(this.models.draw);
      }
      this.models.draw = new Draw({
        source: this.models.polygonSource,
        type: 'Polygon',
      })
      this.models.map.addInteraction(this.models.draw);
    
      this.models.draw.on('drawend', (e) => {
        const coord = e.feature.getGeometry().getCoordinates() //获取最后点坐标
        const area = formatArea(coord);
        this.models.polygonArea += area;
        this.polygonAreaHandler(this.models.polygonArea);
      });
    }

    clearDraw(){
				this.models.polygonSource.clear()
		}
    stopPolygon(){
      if(this.models.draw ){
        this.models.map.removeInteraction(this.models.draw);
        this.models.draw = null;
      }
    }

    setMarker(point) {
      let feature = new Feature({
          geometry: new Point(point),
          style:pointImageStyle('location')
        })
        this.models.positionSource.addFeature(feature);
        this.positionChangeHandler();
    }

    @Emit('positionChange')
    positionChangeHandler(){
      return this.models.positionCoord;
    }

    @Emit('currentPosition')
    backMessage(position){
        return position;
    }
    mounted() {
      this.initMap();
      this.singleclick();
      this.fullscreen.appendChild(this.elTooltip.popperVM.$el)
    }
    @Watch('vectorId')
    updateVectore(val:any){
      if(this.models.geoJsonSource){
          this.models.geoJsonSource.clear();
      }
      if(val){
        this.models.geoJsonSource = loadGeoJson(val,this.models.map);
   
        this.$message.success("区划图层已刷新");
        if(!this.models.polygonLayer){
          this.models.polygonLayer = createLayer(this.models.polygonSource,createStyle("orange","darkgreen","red"));
          this.models.map.addLayer(this.models.polygonLayer);
          if(!this.models.positionLayers){
             this.models.positionLayers = createLayer(this.models.positionSource,pointImageStyle('location'))
            this.models.map.addLayer(this.models.positionLayers);
          }
         
          this.polygonLoaded();
    
      }
    }
  }
  @Emit('polygonLoaded')
  polygonLoaded(){
    console.log('围栏已初始化完成');
  }

    @Watch('polygon')
    updatePolygon(val:any){
      
      if(!this.models.polygonLayer){
        this.models.polygonLayer = createLayer(this.models.polygonSource,createStyle("orange","darkgreen","red"));
        this.models.map.addLayer(this.models.polygonLayer);
      }
      this.models.polygonSource && this.models.polygonSource.clear();
      const geoData = JSON.parse(val);
      if(this.models.polygonSource && val){
       if(!val.startsWith("[[[[")){

        var feature = new Feature({
            geometry: new Polygon(geoData)
          });
          
          this.models.polygonSource.addFeature(feature);
       }else{
         geoData.forEach(dt =>{
          var feature = new Feature({
            geometry: new Polygon(dt)
          });
          this.models.polygonSource.addFeature(feature);
        })
       }
       
      
        this.endModify();
      }else{
        this.models.polygonSource.clear();
      }

    }
   

    // @Watch('polygon')
    // updatePolygon(val: any) {
    //   if (!this.models.polygonSource) return;

    //   // 清空现有要素
    //   this.models.polygonSource.clear();

    //   if (val) {
    //     try {
    //       debugger
    //       // 解析输入数据
    //       const geoData = JSON.parse(val);
          
    //       // 创建几何对象的通用方法
    //       const createGeometry = (coordinates: number[][][] | number[][][][]) => {
    //         // 自动判断类型（Polygon 或 MultiPolygon）
    //         const isMultiPolygon = Array.isArray(coordinates[0][0][0]);

    //         return isMultiPolygon 
    //           ? new MultiPolygon(coordinates as number[][][][])
    //           : new Polygon(coordinates as number[][][]);
    //       };

    //       // 创建要素并设置坐标系（示例使用 WGS84 坐标系）
    //       const feature = new Feature({
    //         geometry: createGeometry(geoData.coordinates || geoData)
    //           .transform('EPSG:4326', 'EPSG:3857') // 转换到地图使用的投影坐标系
    //       });

    //       // 添加要素到数据源
    //       this.models.polygonSource.addFeature(feature);

    //       // 自动缩放到要素范围
         

    //       this.endModify();
    //     } catch (error) {
    //       console.error('数据解析失败:', error);
    //       this.models.polygonSource.clear();
    //     }
    //   }
    // }

    addPolygonSource(val){
      const jsonObj = new GeoJSON().readFeature(val);
    
      this.models.polygonSource.clear();
      this.models.polygonSource.addFeature(jsonObj);
      this.endModify();
    }

    @Watch('position')
    updatePosition(val:any){
      if(!this.models.positionLayers){
        this.models.positionLayers = createLayer(this.models.positionSource,pointImageStyle('location'))
        this.models.map.addLayer(this.models.positionLayers);
      }
        if(val){
            this.models.map.getView().animate({
            center: val, // 新的中心坐标
            zoom: 16,        // 新的缩放级别
            duration: 3000   // 动画持续时间（毫秒）
        });
      }
      this.setMarker(val);
    }
  }
  </script>
  <style scoped>
  .map0 {
    opacity:0.8;
		width: 24px;
		height: 24px;
		background: url(../assets/image/tooltip.png) center center no-repeat;
		background-size: 16px 16px;
		position: absolute;
		right: 60px;
		top: 10px;
		z-index: 200;
		cursor: pointer;
	}
  .map1 {
    opacity:0.5;
		width: 250px;
		height: 40px;
		background: #000 center center no-repeat;
		position: absolute;
		right: 0px;
		top: 0px;
		z-index: 200;
		cursor: pointer;
	}

	.mapbox {
		width: 320px;
		height: 60px;
		display: flex;
		flex-wrap: nowrap;
		justify-content: space-between;
	}

	.mapbox li {
		width: 100px;
		height: 50px;
		margin: 5px 0;
		display: block;
		position: relative;
		cursor: pointer;
	}

	.mapbox li .on {
		height: 16px;
		width: 100px;
		background-color: rgba(0, 0, 0, 0.3);
		color: #fff;
		font-size: 12px;
		position: absolute;
		bottom: 0;
		left: 0;
		display: none;
		text-align: center;
	}
  .mapbox li:hover .on{ display: block;}
	.activeStyle {
		width: 100px;
		height: 50px;
		border: 1px solid #f00;
	}
  .container {
		border: 1px solid #42B983;
		position: relative;
    height:100%;
	}

  .controlbox {
    opacity:0.8;
		position: absolute;
		z-index: 200;
		bottom: 200px;
		width: 18px;
		padding: 5px 7px;
		height: 220px;
		right: 20px;
		border: 1px solid #ccc;
		border-radius: 4px;
		cursor: pointer;
		display: flex;
		align-content: space-between;
		flex-direction: column;
		background-color: #fff;
	}

	.getlength0 {
		width: 18px;
		height: 30px;
		background: url(../assets/image/getnlength.png) center center no-repeat;
		background-size: 16px 16px;
	}

	.getarea0 {
		width: 18px;
		height: 30px;
		background: url(../assets/image/getarea.png) center center no-repeat;
		background-size: 16px 16px;
	}


</style>
